import { getFloorListAPI } from '@/api/floor.api';
import { addRoomAPI, updateRoomAPI } from '@/api/room.api';
import React, { useEffect, useRef, useState } from 'react';
import { Form, Input, Select, Button, MessagePlugin, Space, Dialog, FormInstanceFunctions } from 'tdesign-react';

const { FormItem } = Form;

const statusOptions = [
  { label: '可用', value: 'available' },
  { label: '维护', value: 'maintenance' },
  { label: '占用', value: 'occupied' },
];

const rules = {
  roomNumber: [{ required: true, message: '请输入包间号' }],
  floorId: [{ required: true, message: '请选择楼层' }],
};

export type RoomFormProps = {
  visible: boolean;
  mode: 'add' | 'edit';
  roomData?: any;
  onClose: () => void;
  onSuccess: () => void;
};

const RoomForm: React.FC<RoomFormProps> = ({ visible, mode, roomData, onClose, onSuccess }) => {
  const formRef = useRef<FormInstanceFunctions>();
  const [floorList, setFloorList] = useState<any[]>([]);

  useEffect(() => {
    getFloorListAPI().then(res => {
      if (res.status === 200) {
        setFloorList(res.data.data || []);
      }
    });
  }, []);

  useEffect(() => {
    // 添加一个小延时确保表单已经完全挂载
    const timer = setTimeout(() => {
      if (visible && formRef.current) {
        if (mode === 'edit' && roomData) {
          const floor = floorList.find(f => f.floorNumber === roomData.floorNumber);
          if (floor) {
            formRef.current.setFieldsValue({
              floorId: floor.id,
              roomNumber: roomData.roomNumber,
              description: roomData.description,
              status: roomData.status,
            });
          }
        } else if (mode === 'add') {
          formRef.current.reset();
        }
      }
    }, 0);

    return () => clearTimeout(timer);
  }, [visible, mode, roomData, floorList]);

  const handleSubmit = async () => {
    const values = await formRef.current?.getFieldsValue(true);
    if (mode === 'add') {
      addRoomAPI({
        roomNumber: values?.roomNumber,
        floorId: values?.floorId,
        description: values?.description,
      }).then(res => {
        if (res.status === 200) {
          MessagePlugin.success(res.data.message);
          onSuccess();
          onClose();
        } else if (res.status === 202) {
          MessagePlugin.error(res.data.message);
        }
      }).catch(err => {
        MessagePlugin.error(err.data.message);
      })
    } else if (mode === 'edit') {
      updateRoomAPI({
        id: roomData.id,
        roomNumber: values?.roomNumber,
        floorId: values?.floorId,
        description: values?.description,
        status: values?.status,
      }).then(res => {
        if (res.status === 200) {
          MessagePlugin.success(res.data.message);
          onSuccess();
          onClose();
        }
      });
    }
  };

  return (
    <Dialog
      header={mode === 'add' ? '新建包间' : '编辑包间'}
      visible={visible}
      onClose={onClose}
      footer={
        <Space>
          <Button theme='default' onClick={onClose}>
            取消
          </Button>
          <Button theme="primary" onClick={handleSubmit}>
            {mode === 'add' ? '新增' : '保存'}
          </Button>
        </Space>
      }
    >
      <Form ref={formRef} rules={rules} labelWidth={100}>
        <FormItem label="楼层" name="floorId">
          <Select
            options={floorList.map((f: any) => ({ label: f.floorNumber, value: f.id }))}
            placeholder="请选择楼层"
            disabled={mode === 'edit'}
          />
        </FormItem>
        <FormItem label="包间号" name="roomNumber">
          <Input
            placeholder="请输入包间号，楼层+两位包间号 例如:101,1008"
          />
        </FormItem>
        <FormItem label="描述" name="description">
          <Input placeholder="请输入描述" />
        </FormItem>
        {
          mode === 'edit' && (
            <FormItem label="状态" name="status" rules={[{ required: true, message: '请选择状态' }]}>
              <Select options={statusOptions} placeholder="请选择状态" />
            </FormItem>
          )
        }
      </Form>
    </Dialog>
  );
};

export default RoomForm;
